<?php
namespace app\company\controller;
use think\Db;
use think\Exception;
use think\Request;

class Task extends Base{

    public function _initialize()
    {
        parent::_initialize();
    }
    //我的任务-我参与的
    public function index(){
        $name = I('name','');
        $status = I('status',-1);
        $s_time    = I('s_time','');
        $e_time    = I('e_time','');
        if(!empty($s_time)){
            $where['a.end_time']= ['egt',strtotime($s_time)];
        }
        if(!empty($e_time)){
            $where['a.end_time']= ['elt',strtotime($e_time)];
        }
        if(!empty($s_time)&&!empty($e_time)){
            $where['a.end_time'] = ['between',[strtotime($s_time),strtotime($e_time)]];
        }
        if(!empty($name)){
            $where['a.name'] = ['like',"%{$name}%"];
        }
        if($status != -1){
            $where['a.status'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['b.user_id'] = $user_id;//参与人
        $list = M('com_task a')
            ->join('com_task_relation_take b','a.id=b.task_id','left')
            ->join('users c','c.id=a.principal_user_id','left')
            ->group('a.id')
            ->where($where)
            ->field('a.*,c.name c_name,count(DISTINCT b.id) count_sum')
            ->order('a.create_time desc')
            ->paginate('',false,page_param());
        $this->assign('list',$list);
        return $this->fetch();
    }
    //我的任务-我负责的
    public function index_take(){
        $name = I('name','');
        $status = I('status',-1);
        $s_time    = I('s_time','');
        $e_time    = I('e_time','');
        if(!empty($s_time)){
            $where['a.end_time']= ['egt',strtotime($s_time)];
        }
        if(!empty($e_time)){
            $where['a.end_time']= ['elt',strtotime($e_time)];
        }
        if(!empty($s_time)&&!empty($e_time)){
            $where['a.end_time'] = ['between',[strtotime($s_time),strtotime($e_time)]];
        }
        if(!empty($name)){
            $where['a.name'] = ['like',"%{$name}%"];
        }
        if($status != -1){
            $where['a.status'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['a.principal_user_id'] = $user_id;//负责人
        $list = M('com_task a')
            ->join('com_task_relation_take b','a.id=b.task_id','left')
            ->join('users c','c.id=a.principal_user_id','left')
            ->group('a.id')
            ->where($where)
            ->order('a.create_time desc')
            ->field('a.*,c.name c_name,count(DISTINCT b.id) count_sum')
            ->paginate('',false,page_param());
        $this->assign('list',$list);
        return $this->fetch();
    }
    //任务审核
    public function audit(){
        $name = I('name','');
        $status = I('status',-1);
        $s_time    = I('s_time','');
        $e_time    = I('e_time','');
        if(!empty($s_time)){
            $where['a.end_time']= ['egt',strtotime($s_time)];
        }
        if(!empty($e_time)){
            $where['a.end_time']= ['elt',strtotime($e_time)];
        }
        if(!empty($s_time)&&!empty($e_time)){
            $where['a.end_time'] = ['between',[strtotime($s_time),strtotime($e_time)]];
        }
        if(!empty($name)){
            $where['a.name'] = ['like',"%{$name}%"];
        }
        if($status != -1){
            $where['a.status'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['a.first_check_user_id|a.last_check_user_id'] = $user_id;//初审人和终审人
        $list = M('com_task a')
            ->join('users b','b.id=a.principal_user_id','left')
            ->join('users c','c.id=a.first_check_user_id','left')
            ->join('users d','d.id=a.last_check_user_id','left')
            ->field('a.*,c.name c_name,b.name b_name,d.name d_name')
            ->where($where)
            ->order('a.create_time desc')
            ->paginate('',false,page_param());
        $this->assign('list',$list);
        return $this->fetch();
    }
    
    //任务审核->初审|终审-通过 author:zj
    public function audit_pass()
    {
        $auditId = input('id');
        $check_opinion = input('check_opinion','');     //审核意见
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        if( $err = \app\common\lib\TaskCheck::audit_pass($auditId, $check_opinion) ) return $this->ajaxReturn(1,$err);

        return $this->ajaxReturn(0,'审核通过');

    }
    //任务审核->初审|终审-批量通过 author:zj
    public function audit_pass_list(){
        $ids = explode(',', input('id'));
        $err = '';
        $tmpErr = '';
        foreach($ids as $k=>$v){
            if( $v && intval($v) ){
                $tmpErr = \app\common\lib\TaskCheck::audit_pass($v);
            }
            if(!empty($tmpErr)) {
                $name = $auditInfo = M('com_task')->where('id', $v)->value('name');
                $err .= $name . $tmpErr .";";
            }
        }
        if(!empty($err)){
           return $this->ajaxReturn(1,$err);
        }
        return $this->ajaxReturn(0,$err);
    }

    //任务大厅->任务审核|驳回 author:zj
    public function audit_reject($id = 0, $checkOpinion = ''){
        $auditId = $id ? $id : input('id');
        $check_opinion = $checkOpinion ? : input('check_opinion','');     //审核意见
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        if(!$check_opinion) return $this->ajaxReturn(1,'驳回意见必填');

        $infos = M('com_task')->find($auditId);

        $data = [
            'id'=>$auditId,
            'status'=>5
        ];
        if($infos['status'] == 0 && $infos['first_check_user_id'] == $this->user_id) {
            $data['first_check_opinion'] = $check_opinion;
        }else{
            $data['first_check_opinion'] = $check_opinion;
        }

        //修改状态为5
        DB::startTrans();//开启事务
        try{
            M('com_task')->update($data);
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }
        return $this->ajaxReturn();
    }

    //任务大厅->任务批量驳回 author:zj
    public function audit_reject_list()
    {
        $auditId = explode(',', input('id'));

        foreach($auditId as $k=>$v){
            if($v && intval($v)){
                $this->audit_reject($v,'同意');
            }
        }

        return $this->ajaxReturn();
    }

    //任务大厅->任务撤回 author:zj
    public function audit_withdraw($auditId = 0){
        $auditId = $auditId ? $auditId : input('id');
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        $arr = [
            0=>5,
            1=>0,
        ];
        $res = M('com_task')->find($auditId);
        $status = $arr[$res['status']];

        if($res['record_user_id'] == $this->user_id) $check_status = 1;

        DB::startTrans();//开启事务
        try{
//            M('com_task')->isUpdate(true)->save(['id'=>$auditId, 'status'=>$status]);
            M('com_task')->update(['id'=>$auditId, 'status'=>$status, 'check_status'=>$check_status??0]);
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }
        return $this->ajaxReturn();

    }

    //任务大厅->任务批量撤回 author:zj
    public function audit_withdraw_list(){
        $auditId = explode(',', input('id'));
        foreach($auditId as $k=>$v){
            if(intval($v)){
                $this->audit_withdraw($v);
            }
        }
        return $this->ajaxReturn();
    }

    //任务公告->初审|终审-通过 author:zj
    public function notice_pass()
    {
        $auditId = input('id');
        $check_opinion = input('check_opinion','');     //审核意见
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        if( $err = \app\common\lib\TaskCheck::notice_pass($auditId, $check_opinion) ) return $this->ajaxReturn(1,$err);

        return $this->ajaxReturn(0,'审核通过');
    }

    //任务公告->初审|终审-批量通过 author:zj
    public function notice_pass_list(){
        $ids = explode(',', input('id'));
        $err = '';
        $tmpErr = '';
        foreach($ids as $k=>$v){
            if($v && intval($v)){
                $tmpErr = \app\common\lib\TaskCheck::notice_pass($v);
            }
            if(!empty($tmpErr)) {
                $name = $auditInfo = M('com_task')->where('id', $v)->value('name');
                $err .= $name .':'. $tmpErr .";";
            }
        }

        if(!empty($err)){
            return $this->ajaxReturn(1,$err);
        }

        return $this->ajaxReturn(0,'审核通过');
    }

    //任务公告->公告审核|驳回 author:zj
    public function notice_reject($id = 0,$checkOpinion = '') {
        $auditId = $id ? $id : input('id');
        $check_opinion = $checkOpinion ? :input('check_opinion','');     //审核意见
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        if(!$check_opinion) return $this->ajaxReturn(1,'驳回意见必填');

        $infos = M('com_notice')->find($auditId);

        $data = [
            'id'=>$auditId,
            'status'=>4
        ];
        if($infos['status'] == 0 && $infos['first_check_user_id'] == $this->user_id) {
            $data['first_check_desc'] = $check_opinion;
        }else{
            $data['first_check_desc'] = $check_opinion;
        }
        //修改状态为5
        DB::startTrans();//开启事务
        try{
            M('com_notice')->update(['id'=>$auditId, 'status'=>4]);
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }
        return $this->ajaxReturn();
    }

    //任务公告->任务批量驳回 author:zj
    public function notice_reject_list()
    {
        $auditId = explode(',', input('id'));
        foreach($auditId as $k=>$v){
            if($v && intval($v)){
                $this->notice_reject($v, '同意');
            }
        }
        return $this->ajaxReturn();
    }

    //任务公告->公告审核|撤回 author:zj
    public function notice_withdraw($auditId = 0) {
        $auditId = $auditId ? $auditId : input('id');
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        $arr = [
            0=>4,
            1=>0,
        ];
        $res = M('com_notice')->find($auditId);
        $status = $arr[$res['status']];
        if($res['record_user_id'] == $this->user_id) $check_status = 1;
        DB::startTrans();//开启事务
        try{
//            M('com_notice')->isUpdate(true)->save(['id'=>$auditId, 'status'=>$status]);
            M('com_notice')->update(['id'=>$auditId, 'status'=>$status, 'check_status'=>$check_status??0]);
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }
        return $this->ajaxReturn();
    }

    //任务公告->任务批量撤回 author:zj
    public function notice_withdraw_list(){
        $auditId = explode(',', input('id'));
        foreach($auditId as $k=>$v){
            if(intval($v)){
                $this->notice_withdraw($v);
            }
        }
        return $this->ajaxReturn();
    }

    //我负责的任务->提交 author:zj
    public function audit_send()
    {
        $auditId = input('id');
        //获取当前任务的名称
        $name = input('name', '');
        if(!$auditId || !$name) return $this->ajaxReturn(1,'操作失败');

        //点击提交生产临时事件，如果有相同的名字则不生产
        if($name && $event_id = M('com_event')->where('name', $name)->value('id')){

        }else{
            $eventData = [
                'name'=>$name,
                'com_id'=>$this->com_id,
                'cate_id'=>3,
                'type'=>2,
                'create_time'=>time(),
            ];
            DB::startTrans();//开启事务
            try{
                $event_id = M('com_event')->insertGetId($eventData);
                DB::commit();//回滚
            }catch (\Exception $e){
                DB::rollback();//回滚
                return $this->ajaxReturn(1,$e->getMessage());
            }
        }
        return $this->redirect( url('integral/index_edit'),['event_id'=>$event_id,'task_id'=>$auditId]);

    }

    //任务驳回后.提交 author:zj
    public function audit_sub()
    {
        $auditId = input('id');
        $check_opinion = input('check_opinion','');//审核意见
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        if(!$auditInfo = M('com_task')->where('id', $auditId)->where('record_user_id',$this->user_id)->find()) return $this->ajaxReturn(1,'非法操作，不是相关记录人');

        $saveData = [
            'id'=>$auditId,
            'status'=>0
        ];

        if($this->user_id == $auditInfo['first_check_user_id']){
            $saveData['first_check_opinion'] = $check_opinion;
            $saveData['status'] = 1;
        }

        DB::startTrans();//开启事务
        try{
            M('com_task')->update($saveData);
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1, $e->getMessage());
        }

        //初审通过，发送终审消息
        if($saveData['status'] == 1) { //发送终审消息
            $user_id = $auditInfo['last_check_user_id'];
            $title = '当前有一条任务记录需要您审核(终审)';
            \app\company\logic\Message::send_message($title, $user_id, 1, 2, $auditId);
        }else{
            //提醒初审人，审核
            $user_id = $auditInfo['first_check_user_id'];
            $title = '当前有一条任务记录需要您审核(初审)';
            \app\company\logic\Message::send_message($title, $user_id, 1, 2, $auditId);
        }

        return $this->ajaxReturn(0,'提交成功');
    }

    //任务驳回后.编辑 author:zj
    public function audit_edit()
    {
        $id = I('id', 0);

        if(!$c_i_p_bInfo = M('com_task')->find($id)) return $this->ajaxReturn(1,'数据不存在！');
        $list = $c_i_p_bInfo;

        $where = [
            'com_id'=>$this->com_id,
            'task_id'=>$id,
        ];
        //悬赏任务，type=2  com_task_relation
        if($c_i_p_bInfo['type'] ==2) {
            $c_t_rInfos = M('com_task_relation')->where($where)->select();
            $list['xs'] = $c_t_rInfos;
        }

        //参与人。     com_task_relation_take
        $c_t_r_tInfos = M('com_task_relation_take')->where($where)->select();
        $list['cy'] = $c_t_r_tInfos;

        $task_user_ids = [7, $list['principal_user_id'], $list['first_check_user_id'], $list['last_check_user_id']];//任务的所有相关人员id
        if(isset($list['cy'])){
            $task_user_ids = array_merge($task_user_ids, array_column($list['cy'], 'user_id'));
        }
        if(isset($list['xs'])){
            $task_user_ids = array_merge($task_user_ids, array_column($list['xs'], 'user_id'));
        }
        $task_user_ids = array_unique($task_user_ids);
        //任务的所有相关人员列表
        $take_list = db('users u')
            ->join('com_department d', 'd.id=u.department_id')
            ->where(['u.id'=>['in', $task_user_ids]])
            ->column('u.id, u.name, u.job_number, u.integral_b, d.name d_name');
        //用户
        $users = M('users a')
            ->join('com_department b', 'a.department_id = b.id')
            ->where('a.com_id', $this->com_id)->column('a.id,a.name,b.name as department_name');
        $this->base_department_page();
        $this->assign('info',$list);
        $this->assign('users',$users);
        $this->assign('take_list', $take_list);
        return $this->fetch('issue_edit');
    }

    //任务驳回后.删除 author:zj
    public function audit_del()
    {
        $id = I('id', 0);
        if(!$id) return $this->ajaxReturn(1,'非法操作');

        $c_i_p_bInfo = M('com_task')->find($id);

        //悬赏报名人
        $xs_Ids = M('com_task_relation')->where([
            'com_id'=>$this->com_id,
            'task_id'=>$c_i_p_bInfo['id'],
        ])->column('id');

        //参与人
        $cy_Ids = M('com_task_relation_take')->where([
            'com_id'=>$this->com_id,
            'task_id'=>$c_i_p_bInfo['id'],
        ])->column('id');

        DB::startTrans();//开启事务
        try{
            M('com_task')->where('id',$c_i_p_bInfo['id'])->delete();
            if(count($xs_Ids) > 0) M('com_task_relation')->where('id','in',$xs_Ids)->delete();
            if(count($cy_Ids) > 0) M('com_task_relation')->where('id','in',$cy_Ids)->delete();
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1, $e->getMessage());
        }

        return $this->ajaxReturn(0,'删除成功');
    }

    //公告驳回后.提交 author:zj
    public function notice_sub()
    {
        $auditId = input('id');
        $check_opinion = input('check_opinion','');//审核意见
        if(!$auditId) return $this->ajaxReturn(1,'操作失败');
        if(!$auditInfo = M('com_notice')->where('id', $auditId)->where('record_user_id',$this->user_id)->find()) return $this->ajaxReturn(1,'非法操作，不是相关记录人');

        $saveData = [
            'id'=>$auditId,
            'status'=>0
        ];

        if($this->user_id == $auditInfo['first_check_user_id']){
            $saveData['first_check_opinion'] = $check_opinion;
            $saveData['status'] = 1;
        }

        DB::startTrans();//开启事务
        try{
            M('com_notice')->update($saveData);
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1, $e->getMessage());
        }

        //发送消息
        //初审通过，发送终审消息
        if($saveData['status'] == 1) { //发送终审消息
            $user_id = $auditInfo['last_check_user_id'];
            $title = '当前有一条公告记录需要您审核(终审)';
            \app\company\logic\Message::send_message($title, $user_id, 1, 1, $auditId);
        }else{
            //提醒初审人，审核
            $user_id = $auditInfo['first_check_user_id'];
            $title = '当前有一条公告记录需要您审核(初审)';
            \app\company\logic\Message::send_message($title, $user_id, 1, 1, $auditId);
        }

        return $this->ajaxReturn(0,'提交成功',url('issue_notice'));
    }

    //公告驳回后.编辑 author:zj
    public function notice_edit()
    {
        $id = I('id', 0);

        if(!$c_nInfo = M('com_notice')->find($id)) return $this->ajaxReturn(1,'数据不存在！');
        $list = $c_nInfo;

        $where = [
            'nr.com_id'=>$this->com_id,
            'nr.notice_id'=>$id,
        ];

        $c_n_rInfos = M('com_notice_relation nr')
            ->join('users u', 'u.id=nr.user_id')
            ->join('com_department d', 'd.id=u.department_id')
            ->field('u.id, u.name, u.job_number, u.integral_b, d.name d_name')
            ->where($where)->select();
        $list['list'] = $c_n_rInfos;
        //用户
        $users = M('users a')
            ->join('com_department b', 'a.department_id = b.id')
            ->where('a.com_id', $this->com_id)->column('a.id,a.name,b.name as department_name');
        $this->base_department_page();
        $this->assign('users',$users);
        $this->assign('info',$list);
        $this->assign('users',$users);
        return $this->fetch('issue_notice_edit');
    }

    //公告驳回后.删除 author:zj
    public function notice_del()
    {
        $id = I('id', 0);
        if(!$id) return $this->ajaxReturn(1,'非法操作');

        $c_nInfo = M('com_notice')->find($id);

        //参与人
        $yd_Ids = M('com_notice_relation')->where([
            'com_id'=>$this->com_id,
            'notice_id'=>$c_nInfo['id'],
        ])->column('id');

        DB::startTrans();//开启事务
        try{
            M('com_notice')->where('id',$c_nInfo['id'])->delete();
            if(count($yd_Ids) > 0) M('com_notice_relation')->where('id','in',$yd_Ids)->delete();
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1, $e->getMessage());
        }

        return $this->ajaxReturn(0,'删除成功');
    }

    //公告审核
    public function audit_notice(){
        $name = I('name','');
        $status = I('status',-1);
        $s_time    = I('s_time','');
        $e_time    = I('e_time','');
        if(!empty($s_time)){
            $where['a.end_time']= ['egt',strtotime($s_time)];
        }
        if(!empty($e_time)){
            $where['a.end_time']= ['elt',strtotime($e_time)];
        }
        if(!empty($s_time)&&!empty($e_time)){
            $where['a.end_time'] = ['between',[strtotime($s_time),strtotime($e_time)]];
        }
        if(!empty($name)){
            $where['a.name'] = ['like',"%{$name}%"];
        }
        if($status != -1){
            $where['a.status'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['a.first_check_user_id|a.last_check_user_id'] = $user_id;//初审人和终审人
        $list = M('com_notice a')
            ->join('users b','b.id=a.first_check_user_id','left')
            ->join('users c','c.id=a.last_check_user_id','left')
            ->group('a.id')
            ->where($where)
            ->field('a.*,c.name c_name,b.name b_name')
            ->order('a.create_time desc')
            ->paginate('',false,page_param());
        $this->assign('list',$list);
        return $this->fetch();
    }
    //任务发布
    public function issue(){
        $name = I('name','');
        $status = I('status',-1);
        $s_time    = I('s_time','');
        $e_time    = I('e_time','');
        if(!empty($s_time)){
            $where['a.end_time']= ['egt',strtotime($s_time)];
        }
        if(!empty($e_time)){
            $where['a.end_time']= ['elt',strtotime($e_time)];
        }
        if(!empty($s_time)&&!empty($e_time)){
            $where['a.end_time'] = ['between',[strtotime($s_time),strtotime($e_time)]];
        }
        if(!empty($name)){
            $where['a.name'] = ['like',"%{$name}%"];
        }
        if($status != -1){
            $where['a.status'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['a.record_user_id'] = $user_id;//记录人
        $list = M('com_task a')
            ->join('users b','b.id=a.principal_user_id','left')
            ->join('users c','c.id=a.first_check_user_id','left')
            ->join('users d','d.id=a.last_check_user_id','left')
            ->field('a.*,c.name c_name,b.name b_name,d.name d_name')
            ->where($where)
            ->order('a.create_time desc')
            ->paginate('',false,page_param());
        $this->assign('list',$list);
        return $this->fetch();
    }
    //公告发布
    public function issue_notice(){
        $name = I('name','');
        $status = I('status',-1);
        $s_time    = I('s_time','');
        $e_time    = I('e_time','');
        if(!empty($s_time)){
            $where['a.end_time']= ['egt',strtotime($s_time)];
        }
        if(!empty($e_time)){
            $where['a.end_time']= ['elt',strtotime($e_time)];
        }
        if(!empty($s_time)&&!empty($e_time)){
            $where['a.end_time'] = ['between',[strtotime($s_time),strtotime($e_time)]];
        }
        if(!empty($name)){
            $where['a.name'] = ['like',"%{$name}%"];
        }
        if($status != -1){
            $where['a.status'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['a.record_user_id'] = $user_id;//记录人
        $list = M('com_notice a')
            ->join('users b','b.id=a.first_check_user_id','left')
            ->join('users c','c.id=a.last_check_user_id','left')
            ->group('a.id')
            ->where($where)
            ->order('a.create_time desc')
            ->field('a.*,c.name c_name,b.name b_name')
            ->paginate('',false,page_param());
        $this->assign('list',$list);
        return $this->fetch();
    }
    //新增任务
    public function issue_edit(Request $request){


//        if($request->isPost()){
//            return $this->issue_store($request);
//        }
        //审核权限的用户
        $where_1['a.com_id'] = $this->com_id;
        $list_user = M('com_prize_buckle_relation_users a')
            ->join('users b','b.id = a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.id,b.name,c.name department_name')
            ->where($where_1)->select();
        //用户
        $users = M('users a')
            ->join('com_department b','b.id=a.department_id','left')
            ->field('a.id,a.name,b.name department_name')
            ->where('a.com_id',$this->com_id)->select();
        $this->assign('users',$users);
        $this->assign('info',$list_user);
        $this->base_department_page();
        $this->get_check_people();//默认审核人

//        $this->assign('info',[]);
        return $this->fetch();
    }

    //新增任务提交
    public function issue_store(){
        $params = input();
        $result = $this->validate(
            $params,
            [
                'name'  => 'require|max:50',
                'principal_user_id|任务负责人'  => 'require|gt:0',
                'type|任务类型'  => 'require',
                'end_time|截止日期'  => 'require',
                'del_integral|延期汇报扣分'  => 'require|number',
//                'double_max|扣分上限'  => 'require|number',
                'first_check_user_id|初审人'  => 'require',
                'last_check_user_id|终审人'  => 'require',
            ],
            [
                'name.require'=>'标题必填',
                'name.max'=>'标题最多50个字符',
            ]
        );
        if(true !== $result){
            return $this->ajaxReturn(1, $result);
        }

        if($params['type'] == 2){
            $result = $this->validate(
                $params,
                [
                    'apply_integral|报名奖分'  => 'require|number',
                    'apply_end_time|报名截止时间'  => 'require',
                    'push|消息推送范围'  => 'require',
                ]
            );
            if(true !== $result){
                return $this->ajaxReturn(1, $result);
            }
            if(strtotime($params['apply_end_time']) <= time()){
                return $this->ajaxReturn(1, '报名截止时间必须大于当前时间');
            }
        }
        if(strtotime($params['end_time']) <= time()){
            return $this->ajaxReturn(1, '任务截止时间必须大于当前时间');
        }
        if($params['first_check_user_id'] == $params['last_check_user_id']){
            return $this->ajaxReturn(1,'初审和终审人不能相同');
        }
        if(in_array($params['principal_user_id'],$params['take']??[])){//负责人不能在参与人里面
            return $this->ajaxReturn(1,'负责人不能在参与人里面');
        }
        DB::startTrans();//开启事务
        try{
            $data_take = $params['take']??'';
            $com_task_id = $params['id']??'';                   //--zj--编辑
            $check_opinion = $params['check_opinion']??'';      //--zj--是初审意见
            unset($params['take']);
            $data_push = [];
            if($params['type'] == 2){
                if(!isset($params['push'])){
                    return $this->ajaxReturn(1,'消息推送范围不能为空');
                }
                if(in_array($params['principal_user_id'],$params['push'])){//负责人不能在推送人里面
                    return $this->ajaxReturn(1,'负责人不能在推送人里面');
                }
                $data_push = $params['push'];
                unset($params['push']);
            }else{
                $params['apply_integral'] = 0;
            }

            $params['record_user_id'] = session('user_com')['id'];
            if($params['record_user_id'] == $params['first_check_user_id']){//初审和记录人相同默认初审通过
                $params['status'] = 1;
                $params['first_check_time'] = time();
            }
            if(!empty($params['apply_end_time'])){
                $params['apply_end_time'] = strtotime($params['apply_end_time']);
            }
            $params['create_time'] = time();
            $params['end_time'] = strtotime($params['end_time']);
            $params['com_id'] = $this->com_id;

            //--zj--begin
            if($params['first_check_user_id'] == $this->user_id){
                $params['first_check_opinion'] = $check_opinion;
            }
            //--zj--end

            if(!$com_task_id){
                $id = $com_task_id = M('com_task')->insertGetId($params);
                $com_taskInfo = M('com_task')->find($id);
            }else{
                //--zj--begin
                $com_taskInfo = M('com_task')->where('id', $com_task_id)->where('record_user_id',$this->user_id)->find();

                $params['id'] = $com_task_id;
                $params['status'] = 0;

                if($this->user_id == $com_taskInfo['first_check_user_id']){
                    $params['status'] = 1;
                }
                M('com_task')->update($params);
                $id = $com_task_id;

                //重点。删除原先数据，重新插入
                $delete['com_id'] = $com_taskInfo['com_id'];
                $delete['task_id'] = $com_task_id;
                M('com_task_relation')->where($delete)->delete();
                M('com_task_relation_take')->where($delete)->delete();
                //--zj--end
            }

            if(!empty($data_push)){
                $data_add_1 = [];
                foreach ($data_push as $key=>$value){
                    $data_add_1[] = [
                        'com_id'=>$this->com_id,
                        'task_id'=>$id,
                        'user_id'=>$value,
                    ];
                }
                //新增可以报名的人
                M('com_task_relation')->insertAll($data_add_1);
            }

            if(!empty($data_take)){
                $data_add = [];
                foreach ($data_take as $key=>$value){
                    $data_add[] = [
                        'com_id'=>$this->com_id,
                        'task_id'=>$id,
                        'user_id'=>$value,
                    ];
                }
                //新增参与人
                M('com_task_relation_take')->insertAll($data_add);
            }
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }

        //发送消息--zj--
        //初审通过，发送终审消息
        if($com_task_id && $this->user_id == $com_taskInfo['first_check_user_id']) { //发送终审消息
            $user_id = $com_taskInfo['last_check_user_id'];
            $title = '当前有一条任务记录需要您审核(终审)';
            \app\company\logic\Message::send_message($title, $user_id, 1, 2, $com_task_id);
        }else{
            //提醒初审人，审核
            $user_id = $com_taskInfo['first_check_user_id'];
            $title = '当前有一条任务记录需要您审核(初审)';
            \app\company\logic\Message::send_message($title, $user_id, 1, 2, $com_task_id);
        }

        return $this->ajaxReturn(0,'成功',url(CONTROLLER_NAME.'/issue'));


    }
    //新增公告
    public function issue_notice_edit(Request $request){
        if($request->isPost()){
            return $this->issue_notice_store($request);
        }
//        $this->base_department();
        //审核权限的用户
        $where_1['a.com_id'] = $this->com_id;
        $list_user = M('com_prize_buckle_relation_users a')
            ->join('users b','b.id = a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.id,b.name,c.name department_name')
            ->where($where_1)->select();
        //用户
        $users = M('users a')
            ->join('com_department b','b.id=a.department_id','left')
            ->field('a.id,a.name,b.name department_name')
            ->where('a.com_id',$this->com_id)->select();
        $this->assign('users',$users);
        $this->assign('list_user',$list_user);
        $this->get_check_people();//默认审核人
        $this->base_department_page();

        return $this->fetch();
    }
    //新增公告提交
    public function issue_notice_store(){
        $params = input();

        $noticeId = $params['id']??'';
        $check_opinion = $params['check_opinion']??'';

        $result = $this->validate(
            $params,
            [
                'name|公告名称'  => 'require|max:50',
                'content|公告内容'  => 'require',
                'end_time|截止日期'  => 'require',
                'read_integral|已读奖分'  => 'require',
                'not_read_integral|未读扣分'  => 'require',
                'take|消息推送范围'  => 'require',
                'first_check_user_id|初审人'  => 'require',
                'last_check_user_id|终审人'  => 'require',
            ]
        );
        if(true !== $result){
            return $this->ajaxReturn(1, $result);
        }
        if($params['first_check_user_id'] == $params['last_check_user_id']){
            return $this->ajaxReturn(1,'初审和终审人不能相同');
        }
        DB::startTrans();
        try{
            $data_take = isset($params['take'])?$params['take']:[];
            unset($params['take']);
            $params['record_user_id'] = session('user_com')['id'];
            if($params['record_user_id'] == $params['first_check_user_id']){//初审和记录人相同默认初审通过
                $params['status'] = 1;
                $params['first_check_time'] = time();
            }
            $params['create_time'] = time();
            $params['end_time'] = strtotime($params['end_time']);
            $params['com_id'] = $this->com_id;

            //--zj--begin
            if($params['first_check_user_id'] == $this->user_id){
                $params['first_check_opinion'] = $check_opinion;
            }
            //--zj--end

            if(!$noticeId){
                $id = $noticeId = M('com_notice')->insertGetId($params);
                $com_noticeInfo = M('com_notice')->find($id);
            }else{
                //--zj--begin
                $com_noticeInfo = M('com_notice')->where('id', $noticeId)->where('record_user_id',$this->user_id)->find();
                $params['id'] = $noticeId;
                $params['status'] = 0;

                if($this->user_id == $com_noticeInfo['first_check_user_id']){
                    $params['status'] = 1;
                }
                M('com_notice')->update($params);
                $id = $noticeId;

                //重点。删除原先数据，重新插入
                $delete['com_id'] = $com_noticeInfo['com_id'];
                $delete['notice_id'] = $noticeId;
                M('com_notice_relation')->where($delete)->delete();
                //--zj--end
            }

            if(!empty($data_take)){
                $data_add = [];
                foreach ($data_take as $key=>$value){
                    $data_add[] = [
                        'com_id'=>$this->com_id,
                        'notice_id'=>$id,
                        'user_id'=>$value,
                    ];
                }
                M('com_notice_relation')->insertAll($data_add);
            }else{
                return $this->ajaxReturn(1,'消息推送用户不能为空');
            }
            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $this->ajaxReturn(1,$e->getMessage());
        }

        //发送消息--zj--
        //初审通过，发送终审消息
        if($noticeId && $this->user_id == $com_noticeInfo['first_check_user_id']) { //发送终审消息
            $user_id = $com_noticeInfo['last_check_user_id'];
            $title = '当前有一条公告记录需要您审核(终审)';
            \app\company\logic\Message::send_message($title, $user_id, 1, 1, $id);
        }else{
            //提醒初审人，审核
            $user_id = $com_noticeInfo['first_check_user_id'];
            $title = '当前有一条公告记录需要您审核(初审)';
            \app\company\logic\Message::send_message($title, $user_id, 1, 1, $id);
        }

        return $this->ajaxReturn(0,'成功',url(CONTROLLER_NAME.'/issue_notice'));

    }
    //任务大厅
    public function lobby(){
        $name = I('name','');
        $status = I('status',-1);
        $s_time    = I('s_time','');
        $e_time    = I('e_time','');
        if(!empty($s_time)){
            $where['a.end_time']= ['egt',strtotime($s_time)];
        }
        if(!empty($e_time)){
            $where['a.end_time']= ['elt',strtotime($e_time)];
        }
        if(!empty($s_time)&&!empty($e_time)){
            $where['a.end_time'] = ['between',[strtotime($s_time),strtotime($e_time)]];
        }
        if(!empty($name)){
            $where['a.name'] = ['like',"%{$name}%"];
        }
        if($status != -1){
            $where['c.status'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['c.user_id'] = $user_id;//可报名人id
        $where['a.type'] = 2;//悬赏任务
        $where['a.status'] = 2;//审核通过的
        $list = M('com_task a')
            ->join('users b','b.id=a.principal_user_id','left')
            ->join('com_task_relation c','c.task_id=a.id','left')
            ->group('a.id')
            ->where($where)
            ->field('a.*,b.name b_name')
            ->order('a.create_time desc')
            ->paginate('',false,page_param());
        $list_a = $list->items();
        if(!empty($list_a)){
            foreach ($list_a as $key=>$value){
                $list_a[$key]['count_sum'] = M('com_task_relation')->where('task_id',$value['id'])->where('status',1)->count();
            }
        }
        $this->assign('list',$list);
        $this->assign('list_a',$list_a);
        return $this->fetch();
    }
    //公告大厅
    public function lobby_notice(){
        $name = I('name','');
        $status = I('status',-1);
        $s_time    = I('s_time','');
        $e_time    = I('e_time','');
        if(!empty($s_time)){
            $where['a.end_time']= ['egt',strtotime($s_time)];
        }
        if(!empty($e_time)){
            $where['a.end_time']= ['elt',strtotime($e_time)];
        }
        if(!empty($s_time)&&!empty($e_time)){
            $where['a.end_time'] = ['between',[strtotime($s_time),strtotime($e_time)]];
        }
        if(!empty($name)){
            $where['a.name'] = ['like',"%{$name}%"];
        }
        if($status != -1){
            $where['b.status'] = $status;
        }
        $com_id = $this->com_id;
        $user_id = session('user_com')['id'];
        $where['a.com_id'] = $com_id;
        $where['a.status'] = 2;//审核通过
        $where['b.user_id'] = $user_id;//范围之内
        $list = M('com_notice a')
            ->join('com_notice_relation b','b.notice_id=a.id','left')
            ->group('a.id')
            ->where($where)
            ->field('a.*, b.status as b_status')
            ->order('a.create_time desc')
            ->paginate('',false,page_param());
        $list_a = $list->items();
        if(!empty($list_a)){
            foreach ($list_a as $key=>$value){
                $list_a[$key]['count_sum'] = M('com_notice_relation')->where('notice_id',$value['id'])->where('status',1)->count();
            }
        }
        $this->assign('list',$list);
        $this->assign('list_a',$list_a);
        return $this->fetch();
    }

    //任务详情
    public function task_info(){
        $id = I('id',0);
        if(empty($id)){
            return $this->error('id不能为空');
        }
        //任务信息
        $task = M('com_task a')
            ->join('users b','b.id=a.first_check_user_id','left')
            ->join('users c','c.id=a.last_check_user_id','left')
            ->join('users d','d.id=a.record_user_id','left')
            ->join('users e','e.id=a.principal_user_id','left')
            ->field('a.*,b.name b_name,c.name c_name,d.name d_name,e.name e_name')
            ->where('a.id',$id)->find();
        //参与人
        $user_take = M('com_task_relation_take a')
            ->join('users b','b.id=a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.name,b.job_number,c.name department_name')
            ->where('a.task_id',$task['id'])->select();
        //报名人
        $apply = M('com_task_relation a')
            ->join('users b','b.id=a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.name,b.job_number,b.avatar,a.reason,a.status,c.name department_name')
            ->where('a.task_id',$task['id'])
            ->where('a.status',1)
            ->select();
        //查询记录人奖励分数
        $integral = M('com_config')->where('com_id',$this->com_id)->value('record');
        $this->assign('integral', $integral);
        $this->assign('task',$task);
        $this->assign('user_take',$user_take);
        $this->assign('apply',$apply);
        $this->assign('info',[]);
        return $this->fetch();
    }
    //公告详情
    public function notice_info(){
        $id = I('id',0);
        if(empty($id)){
            return $this->error('id不能为空');
        }
        //公告信息
        $task = M('com_notice a')
            ->join('users b','b.id=a.first_check_user_id','left')
            ->join('users c','c.id=a.last_check_user_id','left')
            ->join('users d','d.id=a.record_user_id','left')
            ->field('a.*,b.name b_name,c.name c_name,d.name d_name')
            ->where('a.id',$id)->find();
        //阅读人
        $read = M('com_notice_relation a')
            ->join('users b','b.id=a.user_id','left')
            ->join('com_department c','c.id=b.department_id','left')
            ->field('b.name,b.job_number,c.name department_name')
            ->where('a.notice_id',$task['id'])
//            ->where('a.status',1)
            ->select();
        //查询记录人奖励分数
        $integral = M('com_config')->where('com_id',$this->com_id)->value('record');

        //更改阅读状态，及发送积分
        if($task['end_time'] > time() && $task['status'] == 2){
            DB::startTrans();
            try{
                M('com_notice_relation')->where(['com_id'=>$this->com_id,'user_id'=>$this->user_id,'notice_id'=>$id])->update(['status'=>1]);
                //发放阅读奖励
                //更改用户的阅读状态，发送积分
                $status = M('com_notice_relation')->where(['com_id'=>$this->com_id,'user_id'=>$this->user_id,'notice_id'=>$id])->value('status');
                if($status == 0){
                    //阅读奖分
                    $task['user_id'] = $this->user_id;
                    \app\common\lib\SendIntegralNew::add_record_integral($task,$task['read_integral'],0,20,true);
                }
                DB::commit();//提交
            }catch (\Exception $e){
                DB::rollback();//回滚
                return $this->ajaxReturn(1,$e->getMessage());
            }
        }

        $this->assign('integral', $integral);
        $this->assign('task',$task);
        $this->assign('read',$read);
        $this->assign('info',[]);
        return $this->fetch();
    }
    public function prize_buckle_info(){
        $uid = $this->user_id;
        $type = I('type',1);//奖扣类型  1日统计  2月统计  3年统计 默认1
        $time = I('time','');//时间
        if(empty($time)){
            return return_json(1,'时间不能为空');
        }
        if($type == 1){
            $start_time = strtotime($time);
            $end_time = $start_time + 24*3600 - 1;
            $count_time_start =  strtotime(date('Y-m-01',$start_time));
            $count_time_end = strtotime("+1 month -1 day",$count_time_start);
            $max_day = date('d',$count_time_end);
        }elseif ($type == 2){
            $start_time = strtotime($time.'01');
            $end_time = strtotime('+1 month -1 day',$start_time);
            $count_time_start =  strtotime(date('Y-01-01',$start_time));
            $count_time_end = strtotime("+1 year -1 day",$count_time_start);
            $max_month = 12;
        }elseif ($type == 3){
            $start_time = strtotime($time.'0101');
            $end_time = strtotime('+1 year -1 day',$start_time);
            $count_time_end = $end_time;
            $count_time_start =  strtotime("-3 years",$count_time_end);
            $max_year = date('Y',$start_time);
            $min_year = $max_year - 3;
        }
        //奖扣详情状况
        $where_1['create_time'] = ['between',[$start_time,$end_time]];//添加时间
        $where_1['user_id'] = $uid; //添加用户
        $where_1['type'] = 0; //类型  0 日常奖扣
        $res = M('com_integral_log')
            ->where($where_1)
            ->field('COALESCE(sum(if(integral_b>0,integral_b,0)),0) integral_b_add,COALESCE(sum(if(integral_b<0,integral_b,0)),0) integral_a_del,count(id) people_sum')
            ->find();
        if($res['integral_b_add'] == 0 || $res['integral_a_del'] == 0){
            $rate = 0;
        }else{
            if($res['integral_b_add'] < $res['integral_a_del']){
                $rate = round($res['integral_b_add']/($res['integral_b_add']+$res['integral_a_del']),2)*100;
            }else{
                $rate = round($res['integral_a_del']/($res['integral_b_add']+$res['integral_a_del']),2)*100;
            }
        }
        //奖扣详情
        $prize_buckle_info = [
            'total_prize'=>$res['integral_b_add'],
            'total_buckle'=>$res['integral_a_del'],
            'people_sum'=>$res['people_sum'],
            'rate'=>$rate,
        ];
        $where_1_a['create_time'] = ['between',[$count_time_start,$count_time_end]];//添加时间
        $where_1_a['user_id'] = $uid; //添加用户
        $where_1_a['type'] = 0; //类型  0 日常奖扣
        $data_total = M('com_integral_log')
            ->where($where_1_a)
            ->field('create_time last_check_time,if(integral_b>0,integral_b,0) integral_b_add,if(integral_b<0,integral_b,0) integral_b_del')
            ->select();
        $data_prize=[];//奖分趋势
        $data_buckle=[];//扣分趋势
        $data_people=[];//人次趋势
        $data_rate=[];//比例趋势
        foreach ($data_total as $key=>$value){
            $data_total[$key]['people_sum'] = 1;
        }
        if($type == 1){
            foreach ($data_total as $key=>$value){
                $data_total[$key]['day'] = date('d',$value['last_check_time']);
            }
            for($i=1;$i<=$max_day;$i++){
                $prize = 0;
                $buckle = 0;
                $people = 0;
                foreach ($data_total as $value){
                    if($value['day'] == $i){
                        $prize += $value['integral_b_add'];
                        $buckle += $value['integral_b_del'];
                        $people += $value['people_sum'];
                    }
                }
                if($prize == 0 || $buckle == 0){
                    $rate = 0;
                }else{
                    if($prize < $buckle){
                        $rate = round($prize/($prize+$buckle),2)*100;
                    }else{
                        $rate = round($buckle/($prize+$buckle),2)*100;
                    }
                }
                $data_prize[$i] = $prize;
                $data_buckle[$i] = $buckle;
                $data_people[$i] = $people;
                $data_rate[$i] = $rate;
            }
        }elseif ($type == 2){
            foreach ($data_total as $key=>$value){
                $data_total[$key]['month'] = date('m',$value['last_check_time']);
            }
            for($i=1;$i<=$max_month;$i++){
                $prize = 0;
                $buckle = 0;
                $people = 0;
                foreach ($data_total as $value){
                    if($value['month'] == $i){
                        $prize += $value['integral_b_add'];
                        $buckle += $value['integral_b_del'];
                        $people += $value['people_sum'];
                    }
                }
                if($prize == 0 || $buckle == 0){
                    $rate = 0;
                }else{
                    if($prize < $buckle){
                        $rate = round($prize/($prize+$buckle),2)*100;
                    }else{
                        $rate = round($buckle/($prize+$buckle),2)*100;
                    }
                }
                $data_prize[$i] = $prize;
                $data_buckle[$i] = $buckle;
                $data_people[$i] = $people;
                $data_rate[$i] = $rate;
            }
        }elseif ($type == 3){
            foreach ($data_total as $key=>$value){
                $data_total[$key]['year'] = date('Y',$value['last_check_time']);
            }
            for($i=$min_year;$i<=$max_year;$i++){
                $prize = 0;
                $buckle = 0;
                $people = 0;
                foreach ($data_total as $value){
                    if($value['year'] == $i){
                        $prize += $value['integral_b_add'];
                        $buckle += $value['integral_b_del'];
                        $people += $value['people_sum'];
                    }
                }
                if($prize == 0 || $buckle == 0){
                    $rate = 0;
                }else{
                    if($prize < $buckle){
                        $rate = round($prize/($prize+$buckle),2)*100;
                    }else{
                        $rate = round($buckle/($prize+$buckle),2)*100;
                    }
                }
                $data_prize[$i] = $prize;
                $data_buckle[$i] = $buckle;
                $data_people[$i] = $people;
                $data_rate[$i] = $rate;
            }
        }
        $data = [
            'prize_buckle_info'=>$prize_buckle_info,
            'data_prize'=>$data_prize,
            'data_buckle'=>$data_buckle,
            'data_people'=>$data_people,
            'data_rate'=>$data_rate,
        ];
        return return_json(0,'获取成功',$data);
    }
    //奖扣明细
    public function prize_buckle_detail(){
        $uid = $this->user_id;
        $type = I('type',1);//奖扣类型  1日统计  2月统计  3年统计 默认1
        $time = I('time','');//时间
        if(empty($time)){
            return return_json(1,'时间不能为空');
        }
        if($type == 1){
            $start_time = strtotime($time);
            $end_time = $start_time + 24*3600 - 1;
        }elseif ($type == 2){
            $start_time = strtotime($time.'01');
            $end_time = strtotime('+1 month -1 day',$start_time);
        }elseif ($type == 3){
            $start_time = strtotime($time.'0101');
            $end_time = strtotime('+1 year -1 day',$start_time);
        }
        //奖扣详情状况
        $where_1['create_time'] = ['between',[$start_time,$end_time]];//添加时间
        $where_1['user_id'] = $uid; //用户
        $where_1['type'] = 0; //类型  0 日常奖扣
        $res = M('com_integral_log')
            ->where($where_1)
            ->field('COALESCE(sum(if(integral_b>0,integral_b,0)),0) integral_b_add,COALESCE(sum(if(integral_b<0,integral_b,0)),0) integral_a_del,count(id) people_sum')
            ->find();
        if($res['integral_b_add'] == 0 || $res['integral_a_del'] == 0){
            $rate = 0;
        }else{
            if($res['integral_b_add'] < $res['integral_a_del']){
                $rate = round($res['integral_b_add']/($res['integral_b_add']+$res['integral_a_del']),2)*100;
            }else{
                $rate = round($res['integral_a_del']/($res['integral_b_add']+$res['integral_a_del']),2)*100;
            }
        }
        //奖扣详情
        $prize_buckle_info = [
            'total_prize'=>$res['integral_b_add'],
            'total_buckle'=>$res['integral_a_del'],
            'people_sum'=>$res['people_sum'],
            'rate'=>$rate,
        ];
        $where_1_a['a.create_time'] = ['between',[$start_time,$end_time]];//添加时间
        $where_1_a['a.user_id'] = $uid; //用户
        $where_1_a['a.type'] = 0; //类型  0 日常奖扣
        $res = M('com_integral_log a')
            ->join('users b','b.id=a.user_id','left')
            ->where($where_1_a)
            ->order('a.create_time desc')
            ->field('a.create_time,a.integral_b,b.name,')
            ->find();
        $data = [
            'prize_buckle_info'=>$prize_buckle_info,
            'list'=>$res,
        ];
        return return_json(0,'获取成功',$data);
    }
    //添加积分奖扣
    public function add_theme()
    {
        $params = input();
        $result = $this->validate(
            $params,
            [
                'theme' => 'require',
                'first_check_user_id ' => 'require',
                'prize_buckle_time' => 'require',
            ],
            [
                'theme.require' => '主题不能为空',
                'first_check_user_id.require' => '初审人不能为空',
                'prize_buckle_time.require' => '奖扣时间不能为空',
            ]
        );
        if (true !== $result) {
            return return_json(1, $result);
        }
        if ($params['first_check_user_id'] == $params['last_check_user_id']) {
            return return_json(1, '初审和终审人不能是同一人');
        }
        if (count($params['event_id']) > count($params['user_id'])) {
            return return_json(1, '参与人不能为空');
        }
        foreach ($params['user_id'] as $key => $value) {
            if (count($value) != count(array_unique($value))) {
                return return_json(1, '参与人不能重复');
            }
        }
        $uid = $this->user_id;
        $com_id = $this->com_id;
        //添加数据
        DB::startTrans();//开启事务
        try {
            //A分
            $integral_a_add = 0;
            $integral_a_del = 0;
            //B分
            $integral_b_add = 0;
            $integral_b_del = 0;
            //人次
            $people_sum = 0;
            foreach ($params['event_id'] as $key => $value) {
                //查询是否专审事件
                $is_check = M('com_event')->where('id', $value)->value('is_check');
                if ($is_check != 1) {
                    foreach ($params['user_id'][$params['number'][$key]] as $k => $v) {
                        $integral_a = isset($params['integral_a'][$params['number'][$key]][$k]) ? $params['integral_a'][$params['number'][$key]][$k] : 0;
                        $integral_b = isset($params['integral_b'][$params['number'][$key]][$k]) ? $params['integral_b'][$params['number'][$key]][$k] : 0;
                        $piece_rate = isset($params['piece_rate'][$params['number'][$key]][$k]) ? $params['piece_rate'][$params['number'][$key]][$k] : 1;
                        if ($integral_a > 0) {
                            $integral_a_add += (int)$integral_a * $piece_rate;
                        } else {
                            $integral_a_del += (int)$integral_a * $piece_rate;
                        }
                        if ($integral_b > 0) {
                            $integral_b_add += (int)$integral_b * $piece_rate;
                        } else {
                            $integral_b_del += (int)$integral_b * $piece_rate;
                        }
                        $people_sum += 1;
                    }
                } else {
                    //A分
                    $integral_a_add_check = 0;
                    $integral_a_del_check = 0;
                    //B分
                    $integral_b_add_check = 0;
                    $integral_b_del_check = 0;
                    //人次
                    $people_sum_check = 0;
                    foreach ($params['user_id'][$params['number'][$key]] as $k => $v) {
                        $integral_a = isset($params['integral_a'][$params['number'][$key]][$k]) ? $params['integral_a'][$params['number'][$key]][$k] : 0;
                        $integral_b = isset($params['integral_b'][$params['number'][$key]][$k]) ? $params['integral_b'][$params['number'][$key]][$k] : 0;
                        $piece_rate = isset($params['piece_rate'][$params['number'][$key]][$k]) ? $params['piece_rate'][$params['number'][$key]][$k] : 1;
                        if ($integral_a > 0) {
                            $integral_a_add_check += (int)$integral_a * $piece_rate;
                        } else {
                            $integral_a_del_check += (int)$integral_a * $piece_rate;
                        }
                        if ($integral_b > 0) {
                            $integral_b_add_check += (int)$integral_b * $piece_rate;
                        } else {
                            $integral_b_del_check += (int)$integral_b * $piece_rate;
                        }
                        $people_sum_check += 1;
                    }

                    $data_array_check = [
                        'com_id' => $com_id,
                        'first_check_user_id' => $params['first_check_user_id_check'][$v],
                        'last_check_user_id' => $params['last_check_user_id_check'][$v],
                        'record_user_id' => $uid,
                        'copy_user_id' => $params['copy_user_id'],
                        'prize_buckle_time' => strtotime($params['prize_buckle_time']),
                        'integral_a_add' => $integral_a_add_check,
                        'integral_a_del' => $integral_a_del_check,
                        'integral_b_add' => $integral_b_add_check,
                        'integral_b_del' => $integral_b_del_check,
                        'theme' => $params['theme'],
                        'create_time' => time(),
                        'people_sum' => $people_sum_check,
                        'desc' => $params['desc'],
                    ];
                    //初审人和记录人相同跳过初审
                    if ($params['first_check_user_id_check'][$v] == $uid) {
                        $data_array_check['status'] = 1;
                        $data_array_check['first_check_time'] = time();
                        $data_array_check['first_check_opinion'] = $params['first_check_opinion'];
                    }
                    //添加主题数据
                    $theme_id_check = M('com_integral_prize_buckle')->insertGetId($data_array_check);
                    //添加事件数据
                    $data_array_event = [
                        'com_id' => $com_id,
                        'prize_buckle_id' => $theme_id_check,
                        'event_id' => $value,
                        'event_desc' => $params['event_desc'][$key],
                        'img' => isset($params['img'][$key])?implode(',',$params['img'][$key]):'',
                        'create_time' => time(),
                    ];
                    $event_id = M('com_integral_prize_buckle_relation_event')->insertGetId($data_array_event);
                    $event_info = M('com_event')->where('id', $value)->find();
                    //添加参与人
                    foreach ($params['user_id'][$params['number'][$key]] as $k => $v) {
                        $integral_a = isset($params['integral_a'][$params['number'][$key]][$k]) ? $params['integral_a'][$params['number'][$key]][$k] : 0;
                        $integral_b = isset($params['integral_b'][$params['number'][$key]][$k]) ? $params['integral_b'][$params['number'][$key]][$k] : 0;
                        $piece_rate = isset($params['piece_rate'][$params['number'][$key]][$k]) ? $params['piece_rate'][$params['number'][$key]][$k] : 1;
                        $data_array_3 = [
                            'com_id' => $this->com_id,
                            'event_id' => $event_id,
                            'user_id' => $v,
                            'integral_a' => $integral_a,
                            'integral_b' => $integral_b,
                        ];
                        if ($event_info['is_piece'] == 1) {
                            $data_array_3['piece_rate'] = $piece_rate;
                        }//计件事件
                        if ($event_info['is_lottery_ticket'] == 1) {
                            $data_array_3['is_lottery_ticket'] = 1;
                        }//奖票事件
                        M('com_integral_event_relation_users')->insert($data_array_3);
                    }
                }
            }
            if ($people_sum < 1) {
                DB::commit();//提交
                return return_json(0, "成功");
            }
            $data_array_1 = [
                'com_id' => $com_id,
                'first_check_user_id' => $params['first_check_user_id'],
                'last_check_user_id' => $params['last_check_user_id'],
                'record_user_id' => $uid,
                'copy_user_id' => $params['copy_user_id'],
                'prize_buckle_time' => strtotime($params['prize_buckle_time']),
                'integral_a_add' => $integral_a_add,
                'integral_a_del' => $integral_a_add,
                'integral_b_add' => $integral_b_add,
                'integral_b_del' => $integral_b_del,
                'theme' => $params['theme'],
                'create_time' => time(),
                'people_sum' => $people_sum,
                'desc' => $params['desc'],
            ];
            //初审人和记录人相同跳过初审
            if ($params['first_check_user_id'] == $uid) {
                $data_array_1['status'] = 1;
                $data_array_1['first_check_time'] = time();
                $data_array_1['first_check_opinion'] = $params['first_check_opinion'];
            }
            //添加主题数据
            $theme_id = M('com_integral_prize_buckle')->insertGetId($data_array_1);
            //添加事件数据
            foreach ($params['event_id'] as $key => $value) {
                $data_array_2 = [
                    'com_id' => $com_id,
                    'prize_buckle_id' => $theme_id,
                    'event_id' => $value,
                    'event_desc' => $params['event_desc'][$key],
                    'create_time' => time(),
                ];
                $event_id = M('com_integral_prize_buckle_relation_event')->insertGetId($data_array_2);
                $event_info = M('com_event')->where('id', $value)->find();
                //添加参与人
                foreach ($params['user_id'][$params['number'][$key]] as $k => $v) {
                    $integral_a = isset($params['integral_a'][$params['number'][$key]][$k]) ? $params['integral_a'][$params['number'][$key]][$k] : 0;
                    $integral_b = isset($params['integral_b'][$params['number'][$key]][$k]) ? $params['integral_b'][$params['number'][$key]][$k] : 0;
                    $piece_rate = isset($params['piece_rate'][$params['number'][$key]][$k]) ? $params['piece_rate'][$params['number'][$key]][$k] : 1;
                    $data_array_3 = [
                        'com_id' => $com_id,
                        'event_id' => $event_id,
                        'user_id' => $v,
                        'integral_a' => $integral_a,
                        'integral_b' => $integral_b,
                    ];
                    if ($event_info['is_piece'] == 1) {
                        $data_array_3['piece_rate'] = $piece_rate;
                    }//计件事件
                    if ($event_info['is_lottery_ticket'] == 1) {
                        $data_array_3['is_lottery_ticket'] = 1;
                    }//奖票事件
                    M('com_integral_event_relation_users')->insert($data_array_3);
                }
            }
            DB::commit();//提交
            return return_json(0, "成功");
        } catch (\Exception $e) {
            DB::rollback();//回滚
            return return_json(1, $e->getMessage());
        }
    }
    //获取部门用户
    public function get_department(){
        $com_id = $this->com_id;
        //查询用户部门
        $list = db('com_department')->where(['com_id' => $this->com_id])->field('id,name,pid')->select();
        $users = M('users a')
            ->join('com_department b', 'b.id=a.department_id', 'left')
            ->field('a.id,a.name,b.name department_name,b.id department_id')
            ->where('a.com_id', $com_id)
            ->select();
        $users = $this->get_tree_data($list, 0, $users, 'department_id');
        return return_json(1,'获取成功',$users);
    }
    //组成无限级数的分类和该分类的数据
    public function get_tree_data($arr = [], $id = 0, $arr_1 = [], $item)
    {
        $list = [];
        foreach ($arr as $k => $v) {
            if ($v["pid"] == $id) {
                unset($arr[$k]);
                $v["list"] = $this->get_tree_data($arr, $v["id"], $arr_1, $item);
                $data = [];
                foreach ($arr_1 as $key => $value) {
                    if ($value[$item] == $v['id']) {
                        $data[] = $value;
                    }
                }
                $v['data'] = $data;
                $list[] = $v;
            }
        }
        return $list;
    }






}
